﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TransportAbstractionLibrary;
using System.IO;
using TransportAbstractionLibrary.Exceptions;

namespace ReceiveFile
{
    class FileWriter : IProtocolUpperLayer
    {
        Guid id = new Guid("1C0EC415-46C9-477b-9038-611CF503204A");
        IProtocolLowerLayer lowerLayer;
        FileStream fileStream;

        private void RequestMoreData()
        {
            byte[] buffer = new byte[1];
            buffer[0] = 10;
            lowerLayer.Send(buffer);
        }

        #region IProtocolUpperLayer Members

        void IProtocolUpperLayer.Bind(IProtocolLowerLayer lowerLayer)
        {
            if (this.lowerLayer == null)
            {
                this.lowerLayer = lowerLayer;
            }
            else
            {
                throw new ArgumentException("Already bound!");
            }
        }

        void IProtocolUpperLayer.Receive(byte[] data)
        {
            Console.WriteLine("bytes recived: " + data.Length);
            fileStream.Write(data, 0, data.Length);
            fileStream.Flush();
            RequestMoreData();
        }

        void IProtocolUpperLayer.ConnectionClosed()
        {
            Console.WriteLine("Connection closed!");
        }

        public IProtocolLowerLayer LowerLayer
        {
            get { return lowerLayer; }
        }

        void IProtocolUpperLayer.OnException(TALException talException)
        {
            Console.WriteLine("Exception occured: " + talException.ToString());
        }
        #endregion

        #region IProtocolBase Members

        public Guid Id
        {
            get
            {
                return id;
            }
        }

        void IProtocolBase.Initialize()
        {
            fileStream = new FileStream(@"c:\Temp\dump.bin", FileMode.Create);
        }

        public LayerType LayerType
        {
            get
            {
                if (lowerLayer != null)
                {
                    return lowerLayer.LayerType | LayerType.Top;
                }
                else
                {
                    return LayerType.Top;
                }
            }
        }

        public bool SuppressInitialization
        {
            get { return lowerLayer.SuppressInitialization; }
        }

        #endregion

        #region IDisposable Members

        public void Dispose()
        {
            fileStream.Flush();
            fileStream.Dispose();
            lowerLayer.Dispose();
        }
        #endregion
    }
}
